<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="学号" prop="stuId">
        <el-input
          v-model="queryParams.stuId"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="姓名" prop="stuName">
        <el-input
          v-model="queryParams.stuName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名" prop="period">
        <el-input
          v-model="queryParams.period"
          placeholder="请输入任务名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学情分析" prop="learnAnalyse">
        <el-input
          v-model="queryParams.learnAnalyse"
          placeholder="请输入学情分析"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评价指标" prop="reviewIndex">
        <el-input
          v-model="queryParams.reviewIndex"
          placeholder="请输入评价指标"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:list:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:list:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:list:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:list:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleDeleteAll"
        >删除所有数据</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchAdd"
        >批量新增</el-button>
      </el-col>

      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="getList"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="listList"
      height="500px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="学号" align="center" prop="stuId" /> -->
      <el-table-column label="姓名" align="center" prop="stuName" />
      <el-table-column label="任务名" align="center" prop="period" />
      <el-table-column label="学情分析" align="center" prop="learnAnalyse" />
      <el-table-column label="评价指标" align="center" prop="reviewIndex" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="打分类型" align="center" prop="scoreType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.score_type" :value="scope.row.scoreType" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:list:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:list:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改分数信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="stuId">
          <el-select
            v-model="form.stuId"
            placeholder="请选择学号"
            clearable
            filterable
            value-key="stuId"
            :disabled="optType === 'edit'"
            @change="changeStu"
          >
            <el-option
              v-for="dict in infoList"
              :key="dict.stuId"
              :label="`${dict.grade}(${dict.stuName})`"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="stuName">
          <el-input
            v-model="form.stuName"
            placeholder="姓名"
            disabled
          />
        </el-form-item>
        <el-form-item label="打分类型" prop="scoreType">
          <el-select v-model="form.scoreType" placeholder="请选择类型" clearable disabled>
            <el-option
              v-for="dict in dict.type.score_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="任务名" prop="period">
          <el-select
            v-model="form.period"
            placeholder="请选择任务名"
            clearable
            filterable
            value-key="stuId"
            @change="changeTask"
          >
            <el-option
              v-for="(dict, index) in taskNameList"
              :key="index"
              :label="dict.taskName"
              :value="dict"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评价指标" prop="reviewIndex">
          <el-tag v-for="(dict, dictIndex) in dict.type.learn_analyse" :key="dict.value">
            {{ dict.label }}
            <div>
              <div
                v-for="(dict, key) in learnAnalyseObjName[`key${dictIndex}`]"
                :key="dict.value"
                class="subject_score"
              >
                <div class="item">{{ dict }}：</div>
                <el-input-number
                  v-model="learnAnalyseObj[`key${dictIndex}`][key]"
                  :placeholder="`请输入分数${key+1}`"
                  style="width: 50%;"
                  :min="0"
                  :max="10"
                  :precision="0"
                />
              </div>
            </div>
          </el-tag>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="'选择任务'" :visible.sync="showDialog" width="400px" append-to-body>
      <el-form ref="form" :inline="true" label-width="80px">
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="checkTaskOptions" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="(task, i) in taskOptions" :key="i" :label="task">{{ task.taskName }}</el-checkbox>
        </el-checkbox-group>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doNext">确 定</el-button>
        <el-button @click="showDialog = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listList,
  getList,
  delList,
  addList,
  updateList
} from '@/api/system/scoreList'
import { studentInfo } from '@/api/system/studentInfo'
import { taskList } from '@/api/system/taskList'
import { Message } from 'element-ui'
export default {
  name: 'List',
  dicts: ['learn_analyse', 'score_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分数信息表格数据
      listList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stuId: null,
        stuName: null,
        period: null,
        learnAnalyse: null,
        reviewIndex: null,
        score: null,
        scoreType: null,
        other1: null,
        other2: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      optType: 'add',
      infoList: [],
      taskNameList: [],
      learnAnalyseObjName: {
        key0: [],
        key1: [],
        key2: []
      },
      learnAnalyseObj: {
        key0: [],
        key1: [],
        key2: []
      },
      checkAll: false,
      checkTaskOptions: [],
      taskOptions: [],
      isIndeterminate: true,
      showDialog: false
    }
  },
  created() {
    this.getStuList()
    this.getTaskList()
    this.getList()
  },
  methods: {
    handleBatchAdd() {
      this.showDialog = true
    },
    handleCheckAllChange(val) {
      this.checkTaskOptions = val ? this.taskOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.taskOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.taskOptions.length
    },
    /** 查询学生信息列表 */
    getStuList() {
      studentInfo({ pageNum: 1, pageSize: 1000 }).then((response) => {
        this.infoList = response.rows
      })
    },
    getTaskList() {
      taskList().then((response) => {
        this.taskNameList = response.rows
        this.taskOptions = this.taskNameList
      })
    },
    /** 查询分数信息列表 */
    getList() {
      this.loading = true
      listList(this.queryParams).then((response) => {
        this.listList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    changeStu(item) {
      this.form.stuId = item.grade
      this.form.stuName = item.stuName
    },
    changeTask(item) {
      this.form.learnAnalyse = item.learnAnalyse
      this.form.reviewIndex = item.reviewIndex
      if (item.reviewIndex) {
        item.reviewIndex.split(';').forEach((el, key) => {
          this.learnAnalyseObjName[`key${key}`] = el.split(',')
        })
      }
      this.form.period = item.taskName
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stuId: null,
        stuName: null,
        period: null,
        learnAnalyse: null,
        reviewIndex: null,
        score: null,
        scoreType: null,
        remark: null,
        other1: null,
        other2: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加分数信息'
      this.optType = 'add'
      Object.keys(this.learnAnalyseObj).forEach(el => {
        this.learnAnalyseObj[el] = []
      })
      this.optType = 'add'
      this.form.scoreType = '1'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.optType = 'edit'
      getList(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改分数信息'
        if (row.reviewIndex) {
          row.reviewIndex.split(';').forEach((el, key) => {
            this.learnAnalyseObjName[`key${key}`] = el.split(',')
          })
        }
        if (row.score) {
          row.score.split(';').forEach((el, key) => {
            this.learnAnalyseObj[`key${key}`] = el.split(',')
          })
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (!this.form.stuId) {
            Message.error('学号必选！')
            return
          }
          if (!this.form.period) {
            Message.error('任务名必选！')
            return
          }
          let str = ''
          let num = 0
          Object.keys(this.learnAnalyseObj).forEach((el, key) => {
            str = str + this.learnAnalyseObj[el].join(',') + (key < 2 ? ';' : '')
            this.learnAnalyseObj[el].forEach(p => {
              if (p) num += 1
            })
          })
          if (num !== 15) {
            Message.error('所有打分必填！')
            return
          }
          this.form.score = str
          if (this.form.id != null) {
            updateList(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            const params = {
              stuId: this.form.stuId,
              stuName: this.form.stuName,
              period: this.form.period,
              scoreType: this.form.scoreType,
              pageNum: 1,
              pageSize: 10
            }
            listList(params).then((response) => {
              const rows = response.rows
              if (rows.length) {
                this.$modal.msgError(`数据重复，请检查：【学号：${params.stuId}-姓名:${params.stuName}-任务:${params.period}】`)
                return
              }
              addList(this.form).then((response) => {
                this.$modal.msgSuccess('新增成功')
                // this.open = false
                this.getList()
              })
            })
          }
        }
      })
    },

    doNext() {
      this.loading = true
      this.showDialog = false
      const that = this
      let count = 0
      const finishNum = that.infoList.length * that.checkTaskOptions.length
      that.infoList.forEach(el => {
        that.checkTaskOptions.forEach(item => {
          const sObj = {}
          item.reviewIndex.split(';').forEach((s, key) => {
            sObj[`key${key}`] = s.split(',').map(m => that.getRandomScore())
          })
          let str = ''
          Object.keys(sObj).forEach((el, key) => {
            str = str + sObj[el].join(',') + (key < 2 ? ';' : '')
          })
          const obj = {
            'id': null,
            'stuId': el.stuId,
            'stuName': el.stuName,
            'period': item.taskName,
            'learnAnalyse': item.learnAnalyse,
            'reviewIndex': item.reviewIndex,
            'score': str,
            'scoreType': '1',
            'remark': null,
            'other1': null,
            'other2': null
          }
          addList(obj).then((response) => {
            count += 1
            if (finishNum === count) {
              this.loading = false
              that.$modal.msgSuccess('批量新增成功')
              that.getList()
            }
          })
        })
      })
    },
    getRandomScore() {
      return Math.floor(Math.random() * (10 - 6 + 1)) + 6
    },
    handleDeleteAll() {
      listList({ pageNum: 1, pageSize: 1000 }).then((response) => {
        const ids = response.rows.map((item) => item.id)
        ids.length && this.handleDelete({ ids })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || row.ids || this.ids
      this.$modal
        .confirm(row.ids && row.ids.length ? `是否删除所有数据` : `是否删除此条数据`)
        .then(function() {
          return delList(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/list/export',
        {
          ...this.queryParams
        },
        `list_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style rel="stylesheet/scss" scoped lang="scss">

.subject_score {
  display: flex;
  margin-bottom: 5px;
   .item {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 70px;
    color: #606266;
    font-weight: 700;
    text-align: center;

   }
}

::v-deep .el-tag {
  margin-right: 10px;
}
</style>
